Getting Started topic
HowTo-Memory.md
Verified against (version pin):
package:cell—3.1.0package:cell_memory—1.0.1- Checked on: 2026-12-01
- Next review: on any MAJOR/MINOR bump of the above.
Audience: two readers, one contract.
- Human developer — read the narrative and copy the snippets; every snippet is a complete, compilable shape against the pinned versions.
- AI agent — this file is the machine-readable layer map: where each component lives, its live signature, when to use it, when not, and the verification surface (the test suite) that proves the snippets are true.
Package this file is about: package:cell_memory — durable values for
the Mitosis stack. A MemoryCell wraps a domain cell: the domain owns
the value T, the memory cell owns the record (revision, generation,
status). package:cell_memory_firebase has its own guide:
HowTo-Memory-Firebase.md in this directory.
Mirror: packages/cell/guide/HowTo-Memory.md is this guide's
application mirror, written from the Cell's perspective — how a
domain cell gains durability, with the file and Firestore backends in
complete programs. This file is the machinery deep dive; that file is
the wiring view. Keep both in sync on any signature change.
Same-directory dependencies
| Sibling | Role |
|---|---|
packages/cell/guide/HowTo-Memory.md |
The Cell-perspective application mirror of this guide |
packages/cell_tissue_memory/guide/HowTo-Memory.md |
The Tissue-perspective mirror: durable collections and scalars |
packages/cell_tissue/guide/HowTo-Memory.md |
The Tissue usage view: books vs. records, wire format |
HowTo-Memory-Firebase.md |
Firestore store, schema-2 rules, multi-client provenance |
packages/cell_memory/doc/design/memory.md |
The design record: runtime semantics, conflict rules, seams |
packages/cell_memory/doc/seams.md |
The four seams (Instruction / TestCell / Context / EphemeralPolicy) |
packages/cell_memory/lib/src/memory_cell.dart |
The one runtime: mailbox, flush, lifecycle |
packages/cell_memory/test/runtime_test.dart |
The behavioral contract of every rule this guide states |
0. Where to look (do this before inventing a signature)
Never guess a MemoryCell signature. Resolve it from the source tree:
| Look here | For |
|---|---|
packages/cell_memory/lib/cell_memory.dart |
The barrel: every public export |
packages/cell_memory/lib/cell_memory_io.dart |
FileMemoryStore |
packages/cell_memory/lib/src/memory_cell.dart |
MemoryCell.open, MemoryCell.fromNucleus, mailbox, flush, lifecycle |
packages/cell_memory/lib/src/memory_cell_nucleus.dart |
MemoryCellNucleus, MemoryCellSlots, the nucleus composition surface |
packages/cell_memory/lib/src/memory_runtime.dart |
MemoryRuntime — the mutable runtime holder for manual composition |
packages/cell_memory/lib/src/memory_snapshot.dart |
MemorySnapshot, MemoryStatus, MemoryConflictPolicy, MemoryResolution |
packages/cell_memory/lib/src/codec.dart |
MemoryCodec, JsonMemoryCodec, JsonListMemoryCodec, JsonMapMemoryCodec |
packages/cell_memory/lib/src/store.dart |
The store contract: MemoryDraft, MemoryVersion, MemoryCas |
packages/cell_memory/lib/src/policy.dart |
MemoryWritePolicy, MemoryWriteMode, MemoryRetry |
packages/cell_memory/lib/src/scheduler.dart / clock.dart |
ManualScheduler, ManualMemoryClock for deterministic tests |
packages/cell_memory/lib/src/instruction/ |
The nine public instruction classes — the customization seams (§12) |
packages/cell_memory/lib/src/memory_flush.dart |
MemoryFlushContext — the deep-replacement toolkit (§12.2) |
packages/cell_memory/test/runtime_test.dart |
Executable proof of every contract below |
packages/cell_memory/test/instruction_catalog_test.dart |
Executable proof of the instruction catalog contracts |
packages/cell_memory/test/from_nucleus_test.dart |
Executable proof of the surface reconstruction contracts |
packages/cell_memory/test/fuzz_test.dart |
The model-based invariant harness |
Imports
import 'package:cell/cell.dart'; // the domain cells
import 'package:cell_memory/cell_memory.dart'; // MemoryCell, remember, codecs, stores, policy
import 'package:cell_memory/cell_memory_io.dart'; // FileMemoryStore (dart:io only)
Do not import package:cell_memory/src/... internals; the barrel is the
surface.
1. The mental model (read this before the snippets)
- The domain cell owns
T.MemoryCell.valueis aMemorySnapshot—status,revision,generation, flags — never the value. Read the value from the domain cell. - The memory cell owns the record. One baseline per open:
(revision, generation, payloadKey). A flush reads the domain now, encodes, compares the payload key against the baseline, and writes only when they differ. - One FIFO mailbox.
load,save,resolve,unload,attach,detach,close,removeare turns on one queue.close()latches admission; queued turns drain; every admitted future completes exactly once. hydrateis the only way the domain mutates from the store. A load or a conflict adopt writes back throughhydrate; nothing else touches the domain.- Conflicts are protocol, not exceptions to hide. Every write is a
compare-and-swap on
(revision, generation); a lost race routes throughMemoryConflictPolicy.
1.1 AI Agent Guide (layer map)
- Layer: Memory — the durability boundary. Not a Cell factory, not a Flow operator, not a Tissue collection.
- Use when: a value must survive a restart or be shared across processes/devices with conflict handling.
- Do NOT use when: you need graph orchestration (
cell_flow), governed collections (cell_tissue), or a wire protocol (cell_skin). - Do NOT confuse with:
Cell.state(in-memory only) or a Tissue book (row history). Memory persists the latest value of one id.
2. Quick start: a durable counter with rememberState
The shortest real shape: a Cell.state is the domain; rememberState
wires both directions (state → store on update, store → state on load).
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
Future<void> main() async {
final counter = Cell.state<int>(initial: 0);
final memory = await rememberState<int>(
counter,
record: MemoryRecord<int>(
id: 'counter',
store: InMemoryMemoryStore(),
codec: JsonMemoryCodec<int>.value(),
),
strategy: const MemoryStrategy(
write: MemoryWritePolicy(mode: MemoryWriteMode.immediate),
),
);
counter.update(1); // accepted pulse -> immediate write
await memory.save(); // settle barrier; row revision 1, payload 1
print(memory.snapshot.status); // MemoryStatus.clean
print(memory.snapshot.revision); // 1
await memory.close();
}
What just happened:
- The default
MemoryOpenMode.loadread the store (miss) and hydrated nothing. counter.update(1)projected to1, marked dirty, and the immediate policy flushed once.save()is a no-op write (same payload key) — it never duplicates.
Live signature:
Future<MemoryCell<T>> rememberState<T>(
StateHandle<T> state, {
required MemoryRecord<T> record,
T? Function(Pulse pulse)? project,
MemoryStrategy strategy = const MemoryStrategy(),
MemoryInfrastructure infrastructure = const MemoryInfrastructure(),
MemoryGovernance governance = const MemoryGovernance(),
})
3. MemoryCell.open: the full binding surface
rememberState is sugar over open(domain, ...). Use open when the
domain is not a Cell.state or when you need the seams between restore
and attach.
import 'dart:async';
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
Future<void> main() async {
final domain = Cell.state<int>(initial: 0);
final memory = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'streak',
store: InMemoryMemoryStore(),
codec: JsonMemoryCodec<int>.value(),
),
lifecycle: MemoryLifecycle<int>(
read: () => domain.cell.value, // flush reads the domain NOW
hydrate: (value) {
domain.update(value);
return true; // an already-current value is not a refusal
}, // load/adopt writes back
project: (pulse) => pulse.payload as int? ?? 0,
),
strategy: const MemoryStrategy(
conflict: MemoryConflictPolicy.adopt(),
write: MemoryWritePolicy(mode: MemoryWriteMode.debounced),
),
);
await memory.attach(domain.cell, project: (pulse) => pulse.payload as int?);
domain.update(7);
await Future<void>.delayed(const Duration(seconds: 1)); // debounce settles
print(memory.snapshot.dirty); // false after the flush
await memory.close();
}
Rules pinned here:
readdefaults to the domainValueCell.value; a non-ValueCell domain without an explicitMemoryLifecycle.readis anArgumentError.hydrateis optional, butadopt/mergeconflict policies require it; without one the policy must befail.projectreturningnullsuppresses the pulse (no counter, no write).- The open mode is one closed enum:
MemoryOpenMode.load(default),seed,loadOrSeed, anddormant— the formerrestore×persistInitialboolean pair, with no invalid combination.
3.1 The snapshot surface
MemorySnapshot get value; // status, revision, generation, loaded, dirty, attached, lastError, conflict
Stream<Object> get errors; // write failures and ingress encoding failures
bool get loaded, dirty, attached, closed;
Object? get lastError;
MemoryEnvelope? get conflict; // the stored row held while conflicted
MemoryStatus values: unloaded, clean, dirty, saving, conflicted, failed, closed.
4. Codecs: the value boundary
A codec is name + version + encode + decode(fromVersion:); dirtiness and
CAS equality are decided by the codec's payload, never by T.==.
4.1 JSON-shaped values
final intCodec = JsonMemoryCodec<int>.value(); // plain JSON primitives
final listCodec = JsonListMemoryCodec<String>(); // List<String>
final mapCodec = JsonMapMemoryCodec<double>(); // Map<String, double>
// Legacy-friendly spellings still work:
final legacy = JsonMemoryCodec<int>.identity();
4.2 Typed models with mapped/of
class CartItem {
const CartItem(this.sku, this.quantity);
final String sku;
final int quantity;
}
final cartCodec = JsonMemoryCodec<CartItem>.mapped(
toJson: (item) => {'sku': item.sku, 'quantity': item.quantity},
fromJson: (payload) {
final map = payload as Map;
return CartItem(map['sku'] as String, map['quantity'] as int);
},
);
4.3 Versioning with migrations
// v1 stored `{'count': n}`; v2 stores `{'total': n}`.
final v2Codec = JsonMemoryCodec<int>.of(
name: 'orders',
version: 2,
toJson: (n) => {'total': n},
fromJson: (payload) => (payload as Map)['total'] as int,
migrations: {
1: (payload) => (payload as Map)['count'] as int, // fromVersion -> value
},
);
Contract: decode throws only FormatException/TypeError/MemoryCorrupt;
the runtime re-wraps anything else as MemoryCorrupt. verifyOnWrite
asserts the round trip in tests — a codec that cannot decode its own
encoding fails fast.
5. Write policies: when the store hears about a pulse
// 1. Immediate (default): one coalesced flush per pulse burst.
const immediate = MemoryWritePolicy(); // mode: MemoryWriteMode.immediate
// 2. Debounced + maxWait: quiet-period batching with a starvation bound.
const debounced = MemoryWritePolicy(
mode: MemoryWriteMode.debounced,
debounce: Duration(milliseconds: 300),
maxWait: Duration(seconds: 5),
);
// 3. Explicit: nothing writes until save(); the flush-on-close still runs.
const explicit = MemoryWritePolicy(mode: MemoryWriteMode.explicit);
// 4. Retry transient IO failures up to 3 attempts, 200 ms apart.
const retried = MemoryWritePolicy(retry: MemoryRetry(attempts: 3));
- A flush always reads the domain now — never the value from the pulse that scheduled it.
- Equal payload keys mean clean: the same value is never rewritten.
- A retryable
MemoryIoExceptionretries; a conflict never retries through the IO path — it routes through the conflict policy.
5.1 Deterministic debounce with ManualScheduler
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
Future<void> main() async {
final scheduler = ManualScheduler();
final store = InMemoryMemoryStore();
final domain = Cell.state<int>(initial: 0);
final memory = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'beat',
store: store,
codec: JsonMemoryCodec<int>.value(),
),
lifecycle: MemoryLifecycle<int>(
hydrate: (value) {
domain.update(value);
return true; // an already-current value is not a refusal
},
),
strategy: const MemoryStrategy(
conflict: MemoryConflictPolicy.fail(),
write: MemoryWritePolicy(mode: MemoryWriteMode.debounced),
),
infrastructure: MemoryInfrastructure(scheduler: scheduler),
);
await memory.attach(domain.cell);
domain.update(1);
domain.update(2);
print(scheduler.pendingCount); // 2 timers armed: debounce + maxWait
scheduler.elapse(); // fire the quiet-period timer
await memory.save(); // settle barrier
print((await store.read('beat'))!.payload); // 2 — the latest value
await memory.close();
}
6. Conflicts: the compare-and-swap protocol
Every write carries expected = (revision, generation). When the store
holds a different row, the policy decides:
// fail: report + suspend autosave until resolve()
const failPolicy = MemoryConflictPolicy.fail();
// overwrite: rebase to the stored row and retry (still CAS-protected)
const overwritePolicy = MemoryConflictPolicy.overwrite();
// adopt (default): decode the stored row, hydrate the domain, drop local
const adoptPolicy = MemoryConflictPolicy.adopt(); // requires hydrate
// merge: fn(local, remote) -> hydrate -> rebase -> write
const mergePolicy = MemoryConflictPolicy.merge;
6.1 Real shape: two devices, last-writer-loses is not an option
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
Future<void> main() async {
// Device A holds revision 2. Device B writes revision 3 concurrently.
final store = InMemoryMemoryStore();
final domain = Cell.state<int>(initial: 0);
final memory = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'settings-version',
store: store,
codec: JsonMemoryCodec<int>.value(),
),
lifecycle: MemoryLifecycle<int>(
hydrate: (value) {
domain.update(value);
return true; // an already-current value is not a refusal
},
),
strategy: const MemoryStrategy(
conflict: MemoryConflictPolicy.fail(),
write: MemoryWritePolicy(mode: MemoryWriteMode.explicit),
),
);
await memory.attach(domain.cell); // pulses reach the cell
domain.update(1);
await memory.save(); // revision 1
// A concurrent writer wins revision 2 with payload 99.
await store.write(MemoryDraft(
id: 'settings-version',
payload: 99,
codec: 'json',
codecVersion: 1,
generation: memory.snapshot.generation,
), expected: (revision: 1, generation: memory.snapshot.generation!));
domain.update(2);
try {
await memory.save();
} on MemoryConflict catch (conflict) {
print('winner: ${conflict.stored?.payload}'); // 99
// Decide manually, then resume autosave by rebasing:
await memory.resolve(const MemoryResolution.takeRemote());
print(domain.cell.value); // 99 — the stored row was hydrated
}
await memory.close();
}
6.2 The merge shape
final mergeCell = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'lamp',
store: InMemoryMemoryStore(),
codec: JsonMemoryCodec<int>.value(),
),
lifecycle: MemoryLifecycle<int>(
hydrate: (value) {
domain.update(value);
return true; // an already-current value is not a refusal
},
),
strategy: MemoryStrategy(
conflict: MemoryConflictPolicy.merge((local, remote) =>
((local as int?) ?? 0) + ((remote as int?) ?? 0)),
),
);
TTL: MemoryStrategy(ttl: Duration(days: 7)) stamps expiresAt on every
committed row; expired rows read as absent and a create wins over them; a
vanished row under ttl recreates once instead of conflicting.
7. Lifecycle: unload, remove, close
Future<void> main() async {
final store = InMemoryMemoryStore();
final domain = Cell.state<int>(initial: 0);
final memory = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'job',
store: store,
codec: JsonMemoryCodec<int>.value(),
),
lifecycle: MemoryLifecycle<int>(
hydrate: (value) {
domain.update(value);
return true; // an already-current value is not a refusal
},
),
strategy: const MemoryStrategy(
conflict: MemoryConflictPolicy.fail(),
write: MemoryWritePolicy(mode: MemoryWriteMode.explicit),
),
infrastructure: const MemoryInfrastructure(ownsStore: true),
);
await memory.attach(domain.cell);
domain.update(1);
await memory.save(); // revision 1
await memory.unload(); // flush-if-dirty, detach, forget baseline; record remains
// The cell is now closed. Restore the record into a fresh open:
final reopened = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'job',
store: store,
codec: JsonMemoryCodec<int>.value(),
),
lifecycle: MemoryLifecycle<int>(
hydrate: (value) {
domain.update(value);
return true; // an already-current value is not a refusal
},
),
strategy: const MemoryStrategy(
conflict: MemoryConflictPolicy.fail(),
),
infrastructure: const MemoryInfrastructure(
ownsStore: true, // unload did not close the store; the new owner will
),
);
await reopened.attach(domain.cell);
print(reopened.snapshot.revision); // 1 — the durable record survived
// detach: false keeps the observer, so the next pulse recreates the row.
await reopened.remove(detach: false); // delete the record; baseline cleared
await reopened.save(); // nothing to write (no baseline, nothing touched)
domain.update(2);
await reopened.save(); // new life: revision 1 under a fresh generation
await reopened.close(); // idempotent; closes the store because ownsStore
}
unload()keeps the durable record and stops emitting;remove()deletes it and frees a new generation.close()is idempotent — including two calls made before the first turn runs — and releases an owned store exactly once.- A failed
opennever leaks: the error stream closes and an owned store is closed before the error rethrows.
8. Observing the record: events and errors
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
Future<void> main() async {
final domain = Cell.state<int>(initial: 0);
final memory = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'seen',
store: InMemoryMemoryStore(),
codec: JsonMemoryCodec<int>.value(),
),
lifecycle: MemoryLifecycle<int>(
hydrate: (value) {
domain.update(value);
return true; // an already-current value is not a refusal
},
),
strategy: const MemoryStrategy(
conflict: MemoryConflictPolicy.fail(),
write: MemoryWritePolicy(mode: MemoryWriteMode.explicit),
),
);
memory.errors.listen((error) => print('reported: $error'));
Cell.observe<Pulse<int>>(
source: memory,
effect: (pulse) {
final event = (pulse as MemoryPulse<int>).event;
print('$event revision=${pulse.revision} payload=${pulse.payload}');
},
);
await memory.attach(domain.cell);
domain.update(3); // applied
await memory.save(); // stored
await memory.unload(); // unloaded
}
MemoryEvent: loaded, applied, stored, conflicted, resolved, failed, unloaded, removed. Failures are reported on errors and never thrown
through the observer path.
9. Seams: deputies, allow, unmodifiable
final loadOnly = await memory.deputy(
testRule: MemoryCell.allow({MemoryAction.load}),
);
await loadOnly.load(); // allowed
// await loadOnly.save(); // StateError('save rejected') — no store call
final readOnly = memory.unmodifiable;
// Every durability method returns a future completing with UnsupportedError.
try {
await readOnly.save();
} on UnsupportedError catch (error) {
print(error.message); // 'MemoryCell: cannot call save() on the read-only view.'
}
final restricted = MemoryCell.allow({MemoryAction.save, MemoryAction.close});
MemoryAction:apply, load, save, resolve, unload, attach, detach, close, remove.allowfails closed: unknown objects are denied (the framework's internal command plumbing stays explicitly exempt).- Deputies share the principal's runtime — store, baseline, mailbox — and can only narrow.
- This is governance narrowing (the same catalog, a stricter gate). Capability narrowing — different instructions per surface — is the instruction catalog's job (§12.1, §12.3). The two compose: a deputy over a customized view keeps the custom catalog and the narrower gate.
10. Stores: in-memory and file
import 'dart:io';
import 'package:cell_memory/cell_memory.dart';
import 'package:cell_memory/cell_memory_io.dart';
Future<void> main() async {
final memoryStore = InMemoryMemoryStore(); // tests, replay hosts
final fileStore = FileMemoryStore.directory(
Directory('counter_data'),
); // one JSON file per id
// ... open cells on either store; both run the same CAS contract.
}
The store contract every backend implements:
Future<MemoryEnvelope?> read(String id);
Future<MemoryEnvelope> write(MemoryDraft draft, {MemoryVersion? expected});
Future<void> remove(String id, {MemoryVersion? ifVersion});
Future<List<String>> list();
Future<int> purgeExpired({DateTime? now});
Future<void> close(); // idempotent; post-close calls throw StateError
MemoryStoreCapabilities get capabilities;
writereturns the committed envelope; the store assigns the revision through the sharedMemoryCas.deciderule engine.- The id grammar is
^[A-Za-z0-9._-]{1,128}$(not.or..).
11. Testing with virtual time
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
Future<void> main() async {
final scheduler = ManualScheduler();
final clock = ManualMemoryClock();
final store = InMemoryMemoryStore(clock: clock);
final domain = Cell.state<int>(initial: 0);
final memory = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'ephemeral',
store: store,
codec: JsonMemoryCodec<int>.value(),
),
lifecycle: MemoryLifecycle<int>(
hydrate: (value) {
domain.update(value);
return true; // an already-current value is not a refusal
},
),
strategy: const MemoryStrategy(
conflict: MemoryConflictPolicy.fail(),
ttl: Duration(minutes: 5),
),
infrastructure: MemoryInfrastructure(
scheduler: scheduler,
clock: clock,
),
);
await memory.attach(domain.cell);
domain.update(1);
await memory.save();
clock.advance(const Duration(minutes: 6));
print(await store.read('ephemeral')); // null — expired
await memory.close();
}
For model-based hardening, packages/cell_memory/test/fuzz_test.dart runs
eight fixed seeds of randomized operations against a fault-injecting store
and checks seven invariants every step — extend that harness for new
backends.
12. User customization: instructions, catalogs, and surface reconstruction
Five customization seams, from shallowest to deepest:
| Seam | Where | Use for |
|---|---|---|
| Codec | MemoryRecord.codec (§4) |
payload encoding, encryption, versioning — try this first |
| Policy | MemoryStrategy (§5, §6) |
when/how writes happen, conflict routing, TTL |
| Instruction | MemoryInfrastructure.customCatalog |
per-action behavior: audit, veto, interpose |
| Flush context | SaveInstruction.writeTurn |
deep replacement of persistence itself |
| Surface | MemoryCell.fromNucleus + core lenses |
capability hiding, per-view catalogs, manual gateways |
Governance always sits above every seam: the cell's test rule vets the
command before the catalog runs, so no customization can bypass
deputy narrowing.
12.1 Instruction catalog: mix-and-match per action
The nine durability actions are nine public, subclassable instructions,
one per MemoryAction:
| Action | Instruction | Replacement seam |
|---|---|---|
apply |
ApplyInstruction |
adopt(cell, pulse, project) |
load |
LoadInstruction |
loadTurn(cell) |
save |
SaveInstruction |
writeTurn(cell, flush, {allowCreate}) |
resolve |
ResolveInstruction |
resolveTurn(cell, resolution) |
attach |
AttachInstruction |
attachTurn(cell, upstream, project) |
detach |
DetachInstruction |
detachTurn(cell) |
unload |
UnloadInstruction |
unloadTurn(cell) |
close |
CloseInstruction |
closeTurn(cell) |
remove |
RemoveInstruction |
removeTurn(cell, {detach, ifVersion}) |
Override one entry and leave the other eight on their defaults via
MemoryInfrastructure.customCatalog:
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
/// Counts every save command before delegating to the standard flush.
class CountingSaveInstruction<T> extends SaveInstruction<T> {
int turns = 0;
@override
Future<MemoryEnvelope?> writeTurn(
MemoryCell<T> cell,
MemoryFlushContext<T> flush, {
bool allowCreate = false,
}) {
turns++;
return super.writeTurn(cell, flush, allowCreate: allowCreate);
}
}
Future<void> main() async {
final store = InMemoryMemoryStore();
final domain = Cell.state<int>(initial: 0);
final counting = CountingSaveInstruction<int>();
final memory = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'c12', store: store, codec: JsonMemoryCodec<int>.identity()),
lifecycle: MemoryLifecycle<int>(
hydrate: (value) { domain.update(value); return true; }),
strategy: const MemoryStrategy(
conflict: MemoryConflictPolicy.fail(),
write: MemoryWritePolicy(mode: MemoryWriteMode.explicit),
),
infrastructure: MemoryInfrastructure(
customCatalog: {MemoryAction.save: counting},
),
);
await memory.attach(domain.cell);
domain.update(1);
await memory.save();
print(counting.turns); // 1 — the command interposed
await memory.close();
}
Rules pinned here:
- Interposition is
super-friendly. Override a turn, do your before/after work, callsuper, and the standard machinery runs. - Every barrier routes through the catalog's save entry.
save(), the scheduled flushes, the seed modes, and theunload/closebarriers all callwriteTurn— one override governs every flush. - A partial catalog is fail-closed. A missing action completes its
command with
StateError('save is not in the catalog'); ingress with noapplyentry is dropped. Partial catalogs are therefore safe capability views (see §12.3).
12.2 Deep replacement: the MemoryFlushContext
A writeTurn override receives a per-turn MemoryFlushContext — the
complete flush toolkit: memoryId, store, codec, policy,
onConflict, ttl, clock, read, hydrate; the live baseline
handles (revision, generation, baselineKey, pendingGeneration,
pulseCounter, touched, conflict, saveSuspended, lastError);
the encoding toolkit (encode, payloadKey, mintGeneration); the
plumbing (reportError, emit, scheduleWrite); and the standard
commit behaviors (adoptCommitted, adoptRemote, suspendConflict).
The motivating example — encrypt at rest without touching the rest of the stack:
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
/// Writes `enc:<encoded>` instead of the codec's raw payload.
class EncryptingWriteInstruction<T> extends SaveInstruction<T> {
@override
Future<MemoryEnvelope?> writeTurn(
MemoryCell<T> cell,
MemoryFlushContext<T> flush, {
bool allowCreate = false,
}) async {
if (flush.saveSuspended) return null;
final before = flush.pulseCounter;
final current = flush.read!();
if (current == null && !flush.codec.acceptsNull) return null;
final wrapped = 'enc:${flush.encode(current)}';
final key = flush.payloadKey(wrapped);
if (key == flush.baselineKey) {
flush.touched = false;
flush.lastError = null;
return null;
}
if (flush.baselineKey == null && !flush.touched && !allowCreate) {
return null;
}
final generation = flush.generation ??
(flush.pendingGeneration ??= flush.mintGeneration());
final committed = await flush.store.write(
MemoryDraft(
id: flush.memoryId,
payload: wrapped,
codec: flush.codec.name,
codecVersion: flush.codec.version,
generation: generation,
),
expected: flush.revision == 0
? null
: (revision: flush.revision, generation: flush.generation!),
);
flush.adoptCommitted(committed, key: key, before: before);
return committed;
}
}
Future<void> main() async {
final store = InMemoryMemoryStore();
final domain = Cell.state<int>(initial: 0);
final memory = await MemoryCell.open<int>(
domain.cell,
record: MemoryRecord<int>(
id: 'enc', store: store, codec: JsonMemoryCodec<int>.identity()),
lifecycle: MemoryLifecycle<int>(
hydrate: (value) { domain.update(value); return true; }),
strategy: const MemoryStrategy(
conflict: MemoryConflictPolicy.fail(),
write: MemoryWritePolicy(mode: MemoryWriteMode.explicit),
),
infrastructure: MemoryInfrastructure(
customCatalog: {MemoryAction.save: EncryptingWriteInstruction<int>()},
),
);
await memory.attach(domain.cell);
domain.update(7);
await memory.save();
print((await store.read('enc'))!.payload); // 'enc:7'
await memory.close();
}
Rules pinned here:
- A custom flush owns the baseline. If it never calls
adoptCommitted(or sets the handles itself), the cell keeps reporting the record as unchanged. - The context stays behind the governance gate — it is only reachable from a catalog entry the cell's test rule already vetted.
- Deep replacement is the last resort. For plain encryption,
prefer an encrypting
MemoryCodecwrapper inMemoryRecord.codec(§4) — the writeTurn path exists for transformations that depend on the flush itself (revision, generation, TTL stamps).
12.3 Surface reconstruction: MemoryCell.fromNucleus
factory MemoryCell.fromNucleus(
MemoryCellNucleus<T> nucleus, {
Map<MemoryAction, Instruction<MemoryCell<T>, Pulse, Pulse>>? catalog,
})
- Same-link views (no
catalog): another handle over the same receptor, catalog, and runtime. Every view reports the same revision — forensic symmetry, lenses on one link. - Derivative views (
catalogprovided): a fresh receptor chain built from the given instructions, walking to the principal for the shared runtime and record state. - Composition from scratch: build a
MemoryRuntime, aMemoryCellSlotsrecord, and aMemoryCellNucleus(all exported), then surface it withfromNucleus.openremains the one-call path;fromNucleusis the composition path.
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
/// The nine defaults, spelled out for an external composition site.
Map<MemoryAction, Instruction<MemoryCell<T>, Pulse, Pulse>>
defaultCatalog<T>() => {
MemoryAction.apply: ApplyInstruction<T>(),
MemoryAction.load: LoadInstruction<T>(),
MemoryAction.save: SaveInstruction<T>(),
MemoryAction.resolve: ResolveInstruction<T>(),
MemoryAction.unload: UnloadInstruction<T>(),
MemoryAction.attach: AttachInstruction<T>(),
MemoryAction.detach: DetachInstruction<T>(),
MemoryAction.close: CloseInstruction<T>(),
MemoryAction.remove: RemoveInstruction<T>(),
};
Future<void> main() async {
final store = InMemoryMemoryStore();
final domain = Cell.state<int>(initial: 0);
final nucleus = MemoryCellNucleus<int>(
slots: (
memoryId: 'view',
store: store,
codec: JsonMemoryCodec<int>.identity(),
policy: const MemoryWritePolicy(mode: MemoryWriteMode.explicit),
scheduler: TimerScheduler(),
clock: SystemMemoryClock(),
source: domain.cell,
read: () => domain.cell.value,
hydrate: null,
project: null,
onConflict: const MemoryConflictPolicy.fail(),
ttl: null,
ownsStore: false,
runtime: MemoryRuntime<int>(),
catalog: defaultCatalog<int>(),
),
);
// The persistence view: full durability surface.
final MemoryCell<int> full =
MemoryCell<int>.fromNucleus(nucleus, catalog: defaultCatalog<int>());
// Capability hiding: the same machinery behind a generic Cell type.
// Only the reactive surface (id, observe, deputy, ...) is visible.
final Cell reactive =
MemoryCell<int>.fromNucleus(nucleus, catalog: defaultCatalog<int>());
print(reactive.id == full.id); // true — one nucleus, two lenses
await full.attach(domain.cell);
domain.update(3);
await full.save();
print((await store.read('view'))!.payload); // 3
// A partial catalog is a fail-closed capability view.
final loadOnly = MemoryCell<int>.fromNucleus(
nucleus,
catalog: {MemoryAction.load: LoadInstruction<int>()},
);
await loadOnly.load(); // allowed
// await loadOnly.save(); // StateError: save is not in the catalog
await full.close();
}
Rules pinned here:
fromNucleusnever bypasses the gate. A catalog override is a capability change under the nucleus's existing test rule; usedeputy/unmodifiable(§9) when you want governance narrowing instead of capability narrowing.- Activation belongs to a surface. The first surface built around a
nucleus activates its receptor; build additional views with
fromNucleus(same-link or derivative), not by re-wrapping an already-activated nucleus with another surface factory.
12.4 The core lenses: Cell.fromNucleus and OpenCell.fromNucleus
The same nucleus can also be handed to the core composition factories, erasing every memory-specific member:
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
/// The nucleus built in §12.3, factored for reuse across lenses.
MemoryCellNucleus<int> viewNucleus(
InMemoryMemoryStore store,
StateHandle<int> domain,
) =>
MemoryCellNucleus<int>(
slots: (
memoryId: 'view',
store: store,
codec: JsonMemoryCodec<int>.identity(),
policy: const MemoryWritePolicy(mode: MemoryWriteMode.explicit),
scheduler: TimerScheduler(),
clock: SystemMemoryClock(),
source: domain.cell,
read: () => domain.cell.value,
hydrate: null,
project: null,
onConflict: const MemoryConflictPolicy.fail(),
ttl: null,
ownsStore: false,
runtime: MemoryRuntime<int>(),
catalog: {
MemoryAction.apply: ApplyInstruction<int>(),
MemoryAction.load: LoadInstruction<int>(),
MemoryAction.save: SaveInstruction<int>(),
MemoryAction.resolve: ResolveInstruction<int>(),
MemoryAction.unload: UnloadInstruction<int>(),
MemoryAction.attach: AttachInstruction<int>(),
MemoryAction.detach: DetachInstruction<int>(),
MemoryAction.close: CloseInstruction<int>(),
MemoryAction.remove: RemoveInstruction<int>(),
},
),
);
Future<void> main() async {
final store = InMemoryMemoryStore();
final domain = Cell.state<int>(initial: 0);
final nucleus = viewNucleus(store, domain);
// The plain reactive lens: no save/load/remove in sight.
final Cell reactive = Cell.fromNucleus(nucleus);
// The manual gateway lens: emit/ingest/link without durability.
final OpenCell gate = OpenCell.fromNucleus(nucleus);
final out = await gate.emit(Pulse<int>(5));
print(out?.payload); // 5
print(gate.id == nucleus.id); // true
}
OpenCell is the core manual-ingress/egress gateway — the shape replay
hosts and bridges use when they must move pulses through a link
without exposing save/load/remove. Prefer
MemoryCell.fromNucleus when the surface should stay memory-typed
(§12.3); reach for the core lenses when the consumer must not even see
that a durability link exists.
12.5 Choosing the seam
| You want to… | Use |
|---|---|
| Audit or log around an action | Subclass the instruction; override handle or the turn; super |
| Transform the stored payload (encryption) | Encrypting MemoryCodec in MemoryRecord.codec — or writeTurn if it needs flush state |
| Replace persistence wholesale | writeTurn + MemoryFlushContext |
Hide save/load/remove from a consumer |
Cell/OpenCell static lenses, or a partial catalog view |
| Narrow permissions under the same runtime | deputy + MemoryCell.allow (§9) |
| Compose a link from parts | MemoryRuntime + MemoryCellSlots + MemoryCellNucleus + fromNucleus |
13. Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
ArgumentError at open: adopt/merge without hydrate |
Default conflict policy is adopt | Pass strategy: MemoryStrategy(conflict: MemoryConflictPolicy.fail()) or a hydrate |
ArgumentError: non-ValueCell domain, no read |
Flush cannot read the domain | Pass lifecycle: MemoryLifecycle(read: () => ...) |
save() writes nothing on a fresh cell |
A save is not a persist | Use MemoryOpenMode.loadOrSeed (or seed) or deliver a pulse first |
MemoryConflict from save() under the fail policy |
A concurrent writer won | Handle it or resolve(...); autosave stays suspended until then |
MemoryCorrupt on load |
Stored bytes/codec mismatch | The record is corrupt; fix the writer or remove the row |
StateError: ... is closed after close/unload |
Admission latches | Open a new cell for further work |
StateError: save is not in the catalog |
A partial-catalog capability view (§12.3) | Add the action to the view's catalog, or use a surface that has it |
A custom writeTurn never writes, but the cell stays dirty |
The replacement flush owns the baseline | Call flush.adoptCommitted (or set the baseline handles) inside writeTurn |
| A pulse arrived but nothing was written | project returned null, or the policy is explicit/disabled |
Check the projector and policy.enabled |
| Stored payload differs from the last pulse | Flush reads the domain now | Update the domain cell, not only the memory cell |
14. AI Agent Guide (summary block)
- Layer: Memory — one durable record per
id; domain cell ownsT. - Live signatures: see sections 2, 3, 4, 5, 6, 7, 12 above; they are
pinned against
cell_memory: 1.0.1andcell: 3.1.0. - Use when: persistence, cross-process/cross-device state, deterministic replay tests, CAS-protected configuration.
- Customize when: one action must audit/veto/replace behavior (§12.1, §12.2), a consumer must not see the durability API (§12.3, §12.4), or a link must be composed from parts (§12.3).
- Do NOT use when: the value must not survive a restart, the domain has no single read/hydrate shape, or you need row history (Tissue).
- Do NOT confuse with:
cell_memory_firebase(a store backend, not the runtime),MemorySnapshot(the view, not the value), orMemoryPulse(the signal, not the record). - Verification surface:
dart testinpackages/cell_memoryis the executable contract:test/guide_snippet_test.dartmirrors every full-program snippet in this guide (a drifted snippet fails the suite),test/runtime_test.dartpins the runtime rules,test/instruction_catalog_test.dartandtest/from_nucleus_test.dartpin the customization contracts,test/fuzz_test.dartruns the 8-seed model-based harness, anddart run tool/gen_pins.dart --checkguards the version pins.
15. Further reading
packages/cell/guide/HowTo-Memory.md— the Cell-perspective application mirror: domain wiring, file and Firestore examples.packages/cell_tissue_memory/guide/HowTo-Memory.md— the Tissue-perspective mirror: durable collections and scalars.HowTo-Memory-Firebase.md— the Firestore backend and schema-2 rules.packages/cell_memory/doc/design/memory.md— runtime semantics D1–D20.packages/cell_memory/doc/seams.md— the four framework seams.packages/cell_memory_live_demo— the two-kiosk demo: hydrate restore, fail-policy provenance reporting, replay with zero divergences.
Classes
-
MemoryCell<
T> Getting Started Features Architecture -
A durable
Cellimplementation that persists its state to a MemoryStore.